package com.jinrustar.httpfileserver.core.http;


import com.jinrustar.httpfileserver.core.ws.WSClient;
import com.jinrustar.httpfileserver.springboot.Application;
import com.jinrustar.httpfileserver.util.CommonUtil;
import com.jinrustar.httpfileserver.util.WebUtils;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;
import io.netty.handler.stream.ChunkedWriteHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;

import static com.jinrustar.httpfileserver.springboot.Application.getLocalIpWithBlock;

public class HttpFileServer {
    private static final Logger logger = LoggerFactory.getLogger(HttpFileServer.class);
//    public static final String DEFAULT_DIR = System.getProperty("user.home") + "/Upload/";

    public static String IP, PORT;
    public static String ipAndPort;

    /*用于发送进度消息给前端页面*/
    /*public static WSClient wsClient;*/

    public void run(final int port, final String dir, Application.StartSuccessCallback startSuccessCallback) throws Exception {
        File dirFile = new File(dir);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }
        String localIp;

        localIp = getLocalIpWithBlock();

        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast("http-decoder", new HttpRequestDecoder());
                            ch.pipeline().addLast("http-aggregator", new HttpObjectAggregator(65536));
                            ch.pipeline().addLast("http-encoder", new HttpResponseEncoder());
                            ch.pipeline().addLast("http-chunked", new ChunkedWriteHandler());
                            ch.pipeline().addLast("fileServerHandler", new HttpFileServerHandler(dir));
                        }
                    });


            /*ChannelFuture f = b.bind("localhost"*//*localIp*//*, port).sync(); 不要指定localhost 或者ip, 否则ip/localhost不能访问 */
            /*ChannelFuture f = b.bind(localIp, port).sync();*/
            ChannelFuture f = b.bind(port).sync();
            ipAndPort = "http://" + localIp + ":" + port;
            IP = localIp;
            PORT = port + "";

            logger.debug("HTTP 文件服务器启动,  {}", ipAndPort);

            if (startSuccessCallback != null) startSuccessCallback.onSuccess(localIp, "httpFileServer");

            /*fLocalIp.channel().closeFuture().sync();*/
            f.channel().closeFuture().sync();

        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }


//    public static void main(String[] args) throws Exception {
//        int port = 8888;
//        if (args.length > 0) {
//            try {
//                port = Integer.parseInt(args[0]);
//            } catch (NumberFormatException e) {
//                port = 8080;
//            }
//        }
//
//        String url = DEFAULT_DIR;
//        if (args.length > 1)
//            url = args[1];
//        new HttpFileServer().run(port, url, null);
//
//
//        logger.debug(System.getProperty("user.dir"));
//    }


}